export default class extends think.Controller {
  async __before() {


    this.ctx.state.token = this.ctx.header["authorization"] || "";
    const tokenSerivce = think.service("token", "api");
    const userId = await tokenSerivce.getUserId(this.ctx.state.token);

    this.ctx.state.userId = userId;

    const publicController = this.config("publicController");
    const publicAction = this.config("publicAction");
    // 如果为非公开，则验证用户是否登录
    const controllerAction = this.ctx.controller + "/" + this.ctx.action;
    if (
      !publicController.includes(this.ctx.controller) &&
      !publicAction.includes(controllerAction) &&
      false
    ) {
      if (this.ctx.state.userId <= 0) {
        return this.fail(401, "请先登录");
      }
    }
  }

  /**
   * 获取时间戳
   * @returns {Number}
   */
  getTime() {
    return parseInt((Date.now() / 1000).toString());
  }

  /**
   * 获取当前登录用户的id
   * @returns {*}
   */
  getLoginUserId() {
    return this.ctx.state.userId;
  }
  /**
   * 设置成SSE流
   */
  setSSE() {
    const { res, req } = this.ctx;
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/event-stream");
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("X-Accel-Buffering", "no");
    // if (req.httpVersion !== "2.0") { }
    res.setHeader("Connection", "keep-alive");

    res.flushHeaders();
  }
}
